package com.lqian.demo04;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 一个线程池为500的线程池,所有线程共享一个ThreadLocal变量
 * 每一个线程执行的时候插入一个大的List集合
 * @author：Melody_LQ
 * @time：2022/8/5 10:43 上午
 */
public class ThreadLocalOOMDemo {
    //线程池大小
    private static final int THREAD_POOL_SIZE = 500;
    //模拟集合数据容量
    private static final int MOCK_DATA_LOOP_LIST_SIZE = 100000;
    private static ThreadLocal<List<User>> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService servicePool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);


        for (int i = 0; i <THREAD_POOL_SIZE ; i++) {
            servicePool.execute(()->{
                threadLocal.set(new ThreadLocalOOMDemo().addBigList());
                System.out.println("----"+Thread.currentThread().getName()+"----");
                threadLocal.remove();
            });
        }



    }

    //返回mock数据
    private List<User> addBigList(){
        List<User> userList = new ArrayList<>(MOCK_DATA_LOOP_LIST_SIZE);
        for (int i = 0; i < MOCK_DATA_LOOP_LIST_SIZE; i++) {
            userList.add(new User("jack"));
        }
        return userList;
    }

}
